<template>
	<view class="login">
		<u-navbar autoBack  title="Login" bgColor="#F54C45" placeholder leftIconColor="#fff" :titleStyle="{color:'#fff'}"></u-navbar>
		<!-- <uni-nav-bar left-icon="left" title="登录" backgroundColor="#F54C45" color="#fff" :border="false"></uni-nav-bar> -->
		<view class="content">
			<!-- 头部logo -->
			<view class="header" style="height: 400rpx;position: relative;color: #fff;letter-spacing: 2px;">
				<image src="@/static/image/login/login1.png" style="position: relative;top: -2px;"></image>
				<view style="position: absolute;left: 15px;bottom:250rpx;font-size: 30px;">WELCOME</view>
				<view style="position: absolute;left: 15px;bottom: 200rpx;font-size: 16px;">Login</view>
			</view>
			<!-- 主体表单 -->
			<view class="main">
				<image src="@/static/image/login/goog.png" style="width: 100px;height: 100px;margin: auto;"></image>
				<!-- #ifdef H5 -->
				<view style="display: flex;align-items: center;">
					<u-code :seconds="sms.seconds" @end="smsEnd" @start="smsStart" ref="uCode" @change="codeChange"></u-code>
					<wInput v-model="phoneData" type="text" maxlength="11" placeholder="请输入手机号码"></wInput>
					<u-button type="primary" plain @tap="getCode" style="width: 250rpx;">{{sms.tips}}</u-button>
				</view>
				<wInput :isShowPass="true" v-model="passData" placeholder="请输入短信验证码"></wInput>
				 <!-- #endif -->
			</view>
			<!-- <view>
				<view>初始化：{{Google.init}}</view>
				<view>登录：{{Google.login}}</view>
			</view> -->
			<!-- #ifdef H5 -->
			<wButton text="登 录" :rotate="isRotate" bgColor="linear-gradient(to bottom, rgba(245, 113, 75, 1), rgba(244, 66, 67, 1))"
			 @click.native="startLogin()"></wButton>
			 <!-- #endif -->
			<!-- #ifdef APP-PLUS -->
			 <wButton text="Google Login" :rotate="isRotate" bgColor="linear-gradient(to bottom, rgba(245, 113, 75, 1), rgba(244, 66, 67, 1))"
			  @click.native="googLogin2()"></wButton>
			 <!-- #endif -->
			<view class="radio-group">
				<checkbox-group v-model="groupValue">
					<checkbox value="agreen" >
						<view style="font-size: 12px;">
							<view style="text-align: center;">I have read and agree</view>
							<view style="display: flex;white-space: nowrap;">
								<u--text type="primary" size="12" text="<User Agreement>" @click="navigatorTo(`/pages/userAgreement/userAgreement?text=关于我们&type=3`)"></u--text>and
								<u--text type="primary" size="12" text="<Privacy Agreement>"  @click="navigatorTo(`/pages/userAgreement/userAgreement?text=隐私策略&type=2`)"></u--text>
							</view>
						</view>
					</checkbox>
				</checkbox-group>
			</view>
			<!-- <navigator url="register" open-type="navigate"><view class="register-btn">注册</view></navigator> -->
			<!-- 其他登录 -->
			<!-- <view class="other_login cuIcon">
				<view class="login_icon">
					<view class="cuIcon-weixin" @tap="login_weixin"></view>
				</view>
			</view> -->

			<!-- 底部信息 -->
			<!-- <view class="footer">
				<navigator url="forget" open-type="navigate">找回密码</navigator>
				<text>|</text>
				<navigator url="register" open-type="navigate">注册账号</navigator>
			</view> -->
		</view>
	</view>
</template>

<script>
	var that, weixinAuthService;
	import wInput from '../../components/watch-login/watch-input.vue' //input
	import wButton from '../../components/watch-login/watch-button.vue' //button
	
	const JYGoogleSignin = uni.requireNativePlugin('JY-GoogleSignin');
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	export default {
		computed: {
			...mapGetters(['userInfo', 'api']),
		},
		data() {
			return {
				
				clientId:'163966241757-2e51ckunv04cqgu46qe8c28ge31lfov0.apps.googleusercontent.com',
				AdroudClientId:'163966241757-upsv8uifiahmgjftjnhke3bmp1590b20.apps.googleusercontent.com',
				groupValue:'agreen',
				phoneData: '13824615862', //用户/电话
				passData: '3838438', //密码
				isRotate: false, //是否加载旋转
				background:'linear-gradient(to bottom, #f94437, #f94437)',
				sms:{
					tips: '',
					seconds: 60,
				},
				from:'',
				loginInfo1:'',
				Google:{
					init:'',
					login:''
				}
			};
		},
		components: {
			wInput,
			wButton,
		},
		onLoad(option) {
			that = this;
			this.from = option.from||''
			// that.getServices()
			
		},
		onShow() {
			// #ifdef APP
			console.log('666');
			// 初始化
			JYGoogleSignin.jy_init({
			    //  安卓的client_id应该是谷歌开发者后台默认Web应用的；iOS的client_id应该是谷歌开发者后台iOS对应的
			    client_id: this.clientId
			}, res=> {
			    //    这里不会有返回数据
				console.log('初始化',res);
				this.Google.init = res
			})
			// #endif
		},
		methods: {
			...mapActions(['set_userInfo','set_userToken']),
			codeChange(text) {
				this.sms.tips = text;
			},
			//获取验证码
			getCode() {
				if(this.$refs.uCode.canGetCode) {
					this.getSms()
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
			//获取短信验证码
			getSms(){
				if (!uni.$u.test.mobile(that.phoneData)) {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '手机号码不正确'
					});
					return;
				}
				uni.showLoading({
					title: '正在获取验证码'
				})
				let params={
					mobile: that.phoneData,
					type: 1
				}
				uni.$u.http.post(this.api.api_v1_sendSms, params).then(res => {
					this.isRotate = false
					if(res.code==200){
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						uni.$u.toast('验证码已发送');
						// 通知验证码组件内部开始倒计时
						this.$refs.uCode.start();
					}
				})
			},
			smsEnd() {
			},
			smsStart() {
			},
			navigatorTo(url){
				uni.navigateTo({
					url: url,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			//
			getServices() {
				// #ifdef APP-PLUS
				plus.oauth.getServices((services) => {
					console.log(services);
					weixinAuthService = services.find((service) => {
						return service.id === 'weixin'
					})
				});
				// #endif
			},
			//谷歌登录2
			googLogin2(){
				// #ifdef APP-PLUS
				JYGoogleSignin.jy_startLogin(res=> {
					console.log(res);
					//  这里会返回登录的结果，如果errorCode = 1，代表错误，可检查msg返回的数据判断；如果errorCode = 0，代表成功，也会在data里面返回登录数据
					if(res.errorCode==0&&res.data.idToken){
						that.googLogin(res.data.idToken)
					}else{
						uni.setClipboardData({
							data: JSON.stringify(res),
							success: function () {
								uni.showToast({
									title: 'system error'// 数据已复制，直接粘贴即可
								});
							}
						});
					}
				})
				// //初始化
				// var mainActivity = plus.android.runtimeMainActivity();  
				// var GoogleSignInOptions = plus.android.importClass("com.google.android.gms.auth.api.signin.GoogleSignInOptions");  
				// var gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  
				// .requestIdToken('163966241757-2e51ckunv04cqgu46qe8c28ge31lfov0.apps.googleusercontent.com')  
				// .requestServerAuthCode('163966241757-2e51ckunv04cqgu46qe8c28ge31lfov0.apps.googleusercontent.com')  
				// .requestEmail()  
				// .requestProfile()  
				// .build();  
				// //创建GoogleClient  
				// var GoogleSignIn = plus.android.importClass("com.google.android.gms.auth.api.signin.GoogleSignIn");  
				// var mGoogleClient = GoogleSignIn.getClient(mainActivity,gso)  
				// var signInIntent =plus.android.invoke(mGoogleClient,'getSignInIntent') 
				// // 退出登录
				// // plus.android.invoke(mGoogleClient, 'signOut')
				// //跳转登录
				// var CODE_REQUEST = 200;  
				// mainActivity.startActivityForResult(signInIntent, CODE_REQUEST);      
				// //获取登录回调  
				// mainActivity.onActivityResult = function(requestCode, resultCode, data) { 
				// 		console.log(requestCode);
				// 		console.log(resultCode);
				// 		console.log(data);
				// 		if (requestCode==CODE_REQUEST){   
				// 			var GoogleSignIn = plus.android.importClass("com.google.android.gms.auth.api.signin.GoogleSignIn");  
				// 			var account = new GoogleSignIn().getLastSignedInAccount(mainActivity)
				// 			let getIdToken = plus.android.invoke(account,'getIdToken')
				// 			// console.log(plus.android.invoke(account,'getId'),'===','unionid,openid')  
				// 			// console.log(plus.android.invoke(account,'getEmail'),'===','email')  
				// 			// console.log(plus.android.invoke(account,'getDisplayName'),'===','nickname')  
				// 			// console.log(plus.android.invoke(account,'getIdToken'),'===','idToken')   
				// 			// console.log(plus.android.invoke(account,'getServerAuthCode'),'===','code，这个是关键code，传递到服务端换access_token令牌')  
				// 			// console.log((plus.android.invoke(account,'getPhotoUrl')||'').toString(),'===','avatarUrl')   
				// 			console.log('8888',getIdToken);
				// 			if(getIdToken){
				// 				that.googLogin(getIdToken)
				// 			}else{
				// 				console.log('未获取到getIdToken');
				// 			}
							
						   
				// 		}  
				// }
				// #endif
				
				
			},
			//谷歌登录
			googLogin(idToken){
				that.isRotate = true
				let params={
					idToken:idToken,
				}
				uni.$u.http.post(this.api.api_v1_loginForGoogle, params).then(res => {
					this.isRotate = false
					console.log(res.code);
					if(res.code==200&&res.data){
						//获取用户信息
						this.set_userInfo(res.data)
						this.set_userToken(res.data.accessToken)
						this.getUserInfo()
						if(this.from){
							uni.redirectTo({
								url: this.from,
								fail() {
									uni.switchTab({
										url: this.from
									});	
								}
							});	
						}else{
							uni.switchTab({
								url: '/pages/tabBar/index/index',
								success: res => {},
								fail: () => {},
								complete: () => {}
							});
						}
					}
				}).catch(err=>{
					this.isRotate = false
				})
				
			},
			
			startLogin() {
				//登录
				if (this.isRotate) {
					//判断是否加载中，避免重复点击请求
					return false;
				}
				// if (!uni.$u.test.mobile(that.phoneData)) {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		position: 'bottom',
				// 		title: '手机号码不正确'
				// 	});
				// 	return;
				// }
				that.isRotate = true
				let params={
					mobile: that.phoneData,
					code: that.passData
				}
				uni.$u.http.post(this.api.api_v1_loginSms, params).then(res => {
					this.isRotate = false
					if(res.code==200&&res.data){
						this.set_userInfo(res.data)
						this.set_userToken(res.data.accessToken)
						// 获取用户信息
						this.getUserInfo()
						if(this.from){
							uni.redirectTo({
								url: this.from,
								fail() {
									uni.switchTab({
										url: that.from
									});	
								}
							});	
						}else{
							uni.switchTab({
								url: '/pages/tabBar/index/index'
							});	
						}
					}
				})

			},
			//获取用户信息
			getUserInfo(){
				let params={
					clientType:2
				}
				uni.$u.http.post(this.api.api_v1_user_getInfo, params).then(res => {
					if(res.code==200&&res.data){
						this.set_userInfo(res.data)
					}
				}).catch(err=>{
					console.log(err);
				})
			},
			//微信登录
			login_weixin() {
				that.oauth('weixin').then((code) => {
					console.log(code);
					let req={
						params: {
							code
						},
						active: 'loginByWeixin',
						showLoad: false
					}
					that.GLOBAL.doCloud('user-center',req).then(res=>{
						if(res.code==0){
							that.set_userInfo(res.userInfo)
							uni.switchTab({
								url: '/pages/index/index'
							});
						}
					})
				}).catch((e) => {
					console.error(e)
				})
			},
			login_weibo() {
				//微博登录
				uni.showToast({
					icon: 'none',
					position: 'bottom',
					title: '...'
				});
			},
			login_github() {
				//github登录
				uni.showToast({
					icon: 'none',
					position: 'bottom',
					title: '...'
				});
			},
			// 获取微信code
			oauth(value) {
				return new Promise((resolve, reject) => {
					// #ifdef APP-PLUS
					weixinAuthService.authorize(function(res) {
						resolve(res.code)
					}, function(err) {
						console.error(err)
						reject(new Error('微信登录失败'))
					});
					// #endif
					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						success(res) {
							resolve(res.code)
						},
						fail(err) {
							console.error('授权登录失败：' + JSON.stringify(err));
							reject(new Error('微信登录失败'))
						}
					})
					// #endif
				})
			},
		}
	}
</script>

<style>
	@import url("../../components/watch-login/css/icon.css");
	@import url("./css/main.css");
</style>
